package com.mazaiting.imqq.ui.activity.message;

import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMTextMessage;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.listener.MessageListHandler;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.newim.listener.MessagesQueryListener;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.exception.BmobException;
import com.mazaiting.imqq.R;
import com.mazaiting.imqq.ui.activity.MainActivity;
import com.mazaiting.imqq.ui.adapter.adapter.ChatAdapter;
import com.mazaiting.imqq.ui.adapter.listener.OnRecyclerViewListener;
import com.mazaiting.imqq.ui.base.BaseActivity;
import com.orhanobut.logger.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天界面
 */
public class ChatActivity extends BaseActivity implements MessageListHandler {
  /**会话*/
  public static final String CONVERSATION = "conversation";
  /**消息管理页面根布局*/
  @BindView(R.id.ll_chat_chat)
  LinearLayout llChat;
  /**下拉刷新*/
  @BindView(R.id.sw_refresh_chat)
  SwipeRefreshLayout swRefresh;
  /**聊天内容*/
  @BindView(R.id.rc_view_chat)
  RecyclerView rcView;

  /**语音相关*/
  /**语音根布局*/
  @BindView(R.id.layout_record_chat)
  RelativeLayout layoutRecord;
  /**录音按钮*/
  @BindView(R.id.iv_record_chat)
  ImageView ivRecord;
  /**提示消息*/
  @BindView(R.id.tv_voice_tips_chat)
  TextView tvVoiceTips;

  /**聊天内容输入框*/
  @BindView(R.id.edit_msg_bottom_bar)
  EditText etMsg;
  /**聊天更多按钮*/
  @BindView(R.id.btn_chat_add_bottom_bar)
  Button btnChatAdd;
  /**聊天表情按钮*/
  @BindView(R.id.btn_chat_emo_bottom_bar)
  Button btnChatEmo;
  /**聊天讲话按钮*/
  @BindView(R.id.btn_speak_bottom_bar)
  Button btnSpeak;
  /**语音聊天按钮*/
  @BindView(R.id.btn_chat_voice_bottom_bar)
  Button btnChatVoice;
  /**文字聊天按钮*/
  @BindView(R.id.btn_chat_keyboard_bottom_bar)
  Button btnChatKeyboard;
  /**文本发送按钮*/
  @BindView(R.id.btn_chat_send_bottom_bar)
  Button btnChatSend;
  /**更多功能*/
  @BindView(R.id.layout_more_bottom_bar)
  LinearLayout llMore;
  /**表情*/
  @BindView(R.id.layout_emo_bottom_bar)
  LinearLayout llEmo;
  /**表情ViewPager*/
  @BindView(R.id.viewpager_emo_bottom_bar)
  ViewPager vpEmo;
  /**底部更多布局*/
  @BindView(R.id.layout_add_bottom_bar)
  LinearLayout llAdd;
  /**底部照片提示文字*/
  @BindView(R.id.tv_picture_chat_add)
  TextView tvPicture;
  /**底部拍摄提示文字*/
  @BindView(R.id.tv_camera_chat_add)
  TextView tvCamera;
  /**底部位置提示文字*/
  @BindView(R.id.tv_location_chat_add)
  TextView tvLocation;
  /**话筒动画*/
  private Drawable[] drawable_Anims;
  /**消息管理*/
  BmobIMConversation mConversationManager;
  /**聊天适配器*/
  ChatAdapter mAdapter;
  private LinearLayoutManager mLayoutManager;

  @Override protected void initData() {
    initSwipeLayout();
    initVoiceView();
    initBottomView();
  }

  /**
   * 初始化底部View
   */
  private void initBottomView() {
    etMsg.setOnTouchListener(new View.OnTouchListener() {
      @Override public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) {
          scrollToBottom();
        }
        return false;
      }
    });
    etMsg.addTextChangedListener(new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        scrollToBottom();
      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(s)) {
          btnChatSend.setVisibility(View.VISIBLE);
          btnChatKeyboard.setVisibility(View.GONE);
          btnChatVoice.setVisibility(View.GONE);
        } else {
          if (btnChatVoice.getVisibility() != View.VISIBLE) {
            btnChatVoice.setVisibility(View.VISIBLE);
            btnChatSend.setVisibility(View.GONE);
            btnChatKeyboard.setVisibility(View.GONE);
          }
        }
      }

      @Override public void afterTextChanged(Editable s) {}
    });
  }

  /**
   * 初始化语音动画资源
   * @Title: initVoiceAnimRes
   */
  private void initVoiceAnimRes() {
    drawable_Anims = new Drawable[]{
        getResources().getDrawable(R.mipmap.chat_icon_voice2),
        getResources().getDrawable(R.mipmap.chat_icon_voice3),
        getResources().getDrawable(R.mipmap.chat_icon_voice4),
        getResources().getDrawable(R.mipmap.chat_icon_voice5),
        getResources().getDrawable(R.mipmap.chat_icon_voice6)};
  }


  @OnClick(R.id.edit_msg_bottom_bar)
  public void onEditClick(View view) {
    if (llMore.getVisibility() == View.VISIBLE) {
      llAdd.setVisibility(View.GONE);
      llEmo.setVisibility(View.GONE);
      llMore.setVisibility(View.GONE);
    }
  }

  @OnClick(R.id.btn_chat_keyboard_bottom_bar)
  public void onKeyClick(View view) {
    showEditState(false);
  }


  @OnClick(R.id.btn_chat_send_bottom_bar)
  public void onSendClick(View view) {
    sendMessage();
  }

  @OnClick(R.id.btn_chat_add_bottom_bar)
  public void onAddClick(){

  }

  /**
   * 发送消息
   */
  private void sendMessage() {
    String text = etMsg.getText().toString();
    if (TextUtils.isEmpty(text.trim())) {
      Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
      return;
    }
    // 发送文本消息
    BmobIMTextMessage msg = new BmobIMTextMessage();
    msg.setContent(text);
    // 可随意设置额外信息
    Map<String, Object> map = new HashMap<>();
    map.put("level", "1");
    msg.setExtraMap(map);
    mConversationManager.sendMessage(msg, listener);
  }

  /**
   * 根据是否点击笑脸来显示文本输入框的状态
   * @param isEmo 用于区分文字和表情
   */
  private void showEditState(boolean isEmo) {
    etMsg.setVisibility(View.VISIBLE);
    btnChatKeyboard.setVisibility(View.GONE);
    btnChatVoice.setVisibility(View.VISIBLE);
    btnSpeak.setVisibility(View.GONE);
    etMsg.requestFocus();
    if (isEmo) {
      llMore.setVisibility(View.VISIBLE);
      llMore.setVisibility(View.VISIBLE);
      llEmo.setVisibility(View.VISIBLE);
      llAdd.setVisibility(View.GONE);
      hideSoftInputView();
    } else {
      llMore.setVisibility(View.GONE);
      showSoftInputView();
    }
  }

  /**
   * 显示软键盘
   */
  private void showSoftInputView() {
    if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
      if (getCurrentFocus() != null)
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
            .showSoftInput(etMsg  , 0);
    }
  }

  /**
   * 下滑到底部
   */
  private void scrollToBottom() {
    mLayoutManager.scrollToPositionWithOffset(mAdapter.getItemCount() - 1, 0);
  }

  /**
   * 初始化声音布局
   */
  private void initVoiceView() {

  }


  /**
   * 初始化下拉布局
   */
  private void initSwipeLayout() {
    swRefresh.setEnabled(true);
    mLayoutManager = new LinearLayoutManager(this);
    rcView.setLayoutManager(mLayoutManager);
    //mAdapter = new ChatAdapter(this, mConversationManager);
    mAdapter = new ChatAdapter(mConversationManager);
    rcView.setAdapter(mAdapter);
    // 第一次加载时
    llChat.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
      @Override public void onGlobalLayout() {
        llChat.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        swRefresh.setRefreshing(true);
        // 自动刷新
        queryMessages(null);
      }
    });
    // 下拉刷新
    swRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override public void onRefresh() {
        BmobIMMessage firstMessage = mAdapter.getFirstMessage();
        queryMessages(firstMessage);
      }
    });
    // 设置RecyclerView的点击事件
    mAdapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
      @Override public void onItemClick(int position) {
        Toast.makeText(ChatActivity.this, "点击" + position + "位置", Toast.LENGTH_SHORT).show();
      }

      @Override public boolean onItemLongClick(int position) {
        // 删除指定聊天消息
        mConversationManager.deleteMessage(mAdapter.getItem(position));
        mAdapter.remove(position);
        return true;
      }
    });
  }

  /**
   * 首次加载，可设置msg为null，下拉刷新的时候，
   * 默认取消息表的第一个msg作为刷新的起始时间点，默认按照消息时间的降序排列
   * @param msg
   */
  private void queryMessages(BmobIMMessage msg) {
    // 查询指定会话的消息记录
    mConversationManager.queryMessages(msg, 10, new MessagesQueryListener() {
      @Override public void done(List<BmobIMMessage> list, BmobException e) {
        swRefresh.setRefreshing(false);
        if (e == null){
          if (null != list && list.size() > 0){
            mAdapter.addMessages(list);
            mLayoutManager.scrollToPositionWithOffset(list.size()-1 ,0);
          }
        } else {
          Toast.makeText(ChatActivity.this, e.getMessage() + "(" + e.getErrorCode() + ")", Toast.LENGTH_SHORT).show();
        }
      }
    });
  }

  /**
   * 消息发送监听器
   */
  public MessageSendListener listener = new MessageSendListener() {
    @Override public void onProgress(int i) {
      super.onProgress(i);
      // 文件类型的消息才有进度值
      Logger.i("onProgress: " + i);
    }

    /**
     * BmobIMMessage{id=6, fromId=a4287fd523, toId=e976bd877c, msgType=txt, content='你好', extra={"level":"1"},
     * conversationType=1, conversationId=e976bd877c, sendStatus=1, receiveStatus=1, createTime=1504768608274, updateTime=1504768608274, isTransient=false}
     * @param bmobIMMessage
     */
    @Override public void onStart(BmobIMMessage bmobIMMessage) {
      super.onStart(bmobIMMessage);
      mAdapter.addMessage(bmobIMMessage);
      etMsg.setText("");
      scrollToBottom();
    }

    @Override public void done(BmobIMMessage bmobIMMessage, BmobException e) {
      mAdapter.notifyDataSetChanged();
      etMsg.setText("");
      scrollToBottom();
      if (e != null) {
        Toast.makeText(ChatActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
      }
    }
  };

  @Override protected void getIntentData() {
    // 获得会话入口
    BmobIMConversation conversation = (BmobIMConversation) getIntent().getSerializableExtra(CONVERSATION);
    // 根据会话入口获得消息管理，聊天页面
    mConversationManager = BmobIMConversation.obtain(BmobIMClient.getInstance(), conversation);
  }

  @OnClick(R.id.tv_left_include_nav)
  public void onBack(){
    newIntent(MainActivity.class, null);
  }

  @Override public void onBackPressed() {
    super.onBackPressed();
    newIntent(MainActivity.class, null);
  }

  @Override protected int getLayoutId() {
    return R.layout.activity_chat;
  }

  @Override
  protected void onResume() {
    //锁屏期间的收到的未读消息需要添加到聊天界面中
    addUnReadMessage();
    //添加页面消息监听器
    BmobIM.getInstance().addMessageListHandler(this);
    // 有可能锁屏期间，在聊天界面出现通知栏，这时候需要清除通知
    BmobNotificationManager.getInstance(this).cancelNotification();
    super.onResume();
  }
  @Override
  protected void onPause() {
    //移除页面消息监听器
    BmobIM.getInstance().removeMessageListHandler(this);
    super.onPause();
  }
  /**
   * 添加未读的通知栏消息到聊天界面
   */
  private void addUnReadMessage() {
    List<MessageEvent> cache = BmobNotificationManager.getInstance(this).getNotificationCacheList();
    if (cache.size() > 0) {
      int size = cache.size();
      for (int i = 0; i < size; i++) {
        MessageEvent event = cache.get(i);
        addMessage2Chat(event);
      }
    }
    scrollToBottom();
  }


  /**
   * 添加消息到聊天界面中
   * @param event
   */
  private void addMessage2Chat(MessageEvent event) {
    BmobIMMessage msg = event.getMessage();
    if (mConversationManager != null && mConversationManager.getConversationId()
        .equals(event.getConversation().getConversationId()) && !msg.isTransient()) {//并且不为暂态消息
      if (mAdapter.findPosition(msg) < 0) {//如果未添加到界面中
        mAdapter.addMessage(msg);
        //更新该会话下面的已读状态
        mConversationManager.updateReceiveStatus(msg);
      }
      scrollToBottom();
    } else {
      Logger.i("不是与当前聊天对象的消息");
    }
  }


  @Override public void onMessageReceive(List<MessageEvent> list) {
    //当注册页面消息监听时候，有消息（包含离线消息）到来时会回调该方法
    for (int i = 0; i < list.size(); i++) {
      addMessage2Chat(list.get(i));
    }
  }
}
